PyTorch入門:テンソルの重要性とは
PyTorchは、ディープラーニング研究や迅速なプロトタイピングに最適な、非常に柔軟で動的なオープンソースフレームワークです。その中心にあるのが テンソル であり、深層学習モデルに必要な数値演算を効率的に処理できるように設計された多次元配列です。自動的に GPU加速 をサポートしています。
1. テンソル構造の理解
PyTorchにおけるすべての入力、出力、およびモデルパラメータはテンソルにカプセル化されています。これらはNumPy配列と同じ役割を果たしますが、 GPUといった専用ハードウェア上で処理されるように最適化されており、ニューラルネットワークに必要な大規模な線形代数演算においてははるかに効率的です。
テンソルを定義する主な属性は以下の通りです:
- 形状:データの次元を定義し、タプル形式(例:画像バッチの場合 $4 \times 32 \times 32$)で表現されます。
- データ型:格納されている要素の数値型を指定します(例:
torch.float32はモデルの重みに、torch.int64はインデックス操作に使用)。 - デバイス:物理的なハードウェアの場所を示します。通常は
'cpu'または'cuda'(NVIDIA GPU)です。
動的グラフと自動微分(Autograd)
PyTorchは命令型実行モデルを使用しており、演算が実行される度に計算グラフが構築されます。これにより、組み込みの自動微分エンジンである Autogradが、テンソル上のすべての演算を追跡できるようになります。ただし、
requires_grad=True というプロパティが設定されている必要があります。これにより、逆伝播中における勾配の計算が容易になります。
TERMINALbash — pytorch-env
> Ready. Click "Run" to execute.
>
TENSOR INSPECTOR Live
Run code to inspect active tensors
Question 1
Which command creates a $5 \times 5$ tensor containing random numbers following a uniform distribution between 0 and 1?
Question 2
If tensor $A$ is on the CPU, and tensor $B$ is on the CUDA device, what happens if you try to compute $A + B$?
Question 3
What is the most common data type (dtype) used for model weights and intermediate calculations in Deep Learning?
Challenge: Tensor Manipulation and Shape
Prepare a tensor for a specific matrix operation.
You have a feature vector $F$ of shape $(10,)$. You need to multiply it by a weight matrix $W$ of shape $(10, 5)$. For matrix multiplication (MatMul) to work, $F$ must be 2-dimensional.
Step 1
What should the shape of $F$ be before multiplication with $W$?
Solution:
The inner dimensions must match, so $F$ must be $(1, 10)$. Then $(1, 10) @ (10, 5) \rightarrow (1, 5)$.
Code:
The inner dimensions must match, so $F$ must be $(1, 10)$. Then $(1, 10) @ (10, 5) \rightarrow (1, 5)$.
Code:
F_new = F.unsqueeze(0) or F_new = F.view(1, -1)Step 2
Perform the matrix multiplication between $F_{new}$ and $W$ (shape $(10, 5)$).
Solution:
The operation is straightforward MatMul.
Code:
The operation is straightforward MatMul.
Code:
output = F_new @ W or output = torch.matmul(F_new, W)Step 3
Which method explicitly returns a tensor with the specified dimensions, allowing you to flatten the tensor back to $(50,)$? (Assume $F$ was $(5, 10)$ initially and is now flattened.)
Solution:
Use the
Code:
Use the
view or reshape methods. The fastest way to flatten is often using -1 for one dimension.Code:
F_flat = F.view(-1) or F_flat = F.reshape(50)